<template>
  <div class="mpvue-picker">
    <div :class="{'pickerMask':showPicker}" @click="maskClick" catchtouchmove="true"></div>
    <div class="mpvue-picker-content " :class="{'mpvue-picker-view-show':showPicker}">
      <div class="mpvue-picker__hd" catchtouchmove="true">
        <div class="mpvue-picker__action" @click="pickerCancel">取消</div>
        <div class="mpvue-picker__action" :style="{color:themeColor}" @click="pickerConfirm">确定</div>
      </div>
      <picker-view indicator-style="height: 40px;" class="mpvue-picker-view" :value="pickerValue" @change="pickerChange">
          <picker-view-column>
            <div class="picker-item" v-for="(item,index) in provinceDataList" :key="index">{{item.name}}</div>
          </picker-view-column>
          <picker-view-column>
            <div class="picker-item" v-for="(item,index) in cityDataList" :key="index">{{item.name}}</div>
          </picker-view-column>
          <picker-view-column>
            <div class="picker-item" v-for="(item,index) in areaDataList" :key="index">{{item.name}}</div>
          </picker-view-column>
		  <picker-view-column>
		    <div class="picker-item" v-for="(item,index) in streetDataList" :key="index">{{item.name}}</div>
		  </picker-view-column>
      </picker-view>
    </div>
  </div>
</template>

<script>
import addressApis from '@/common/services/address.js';
export default {
  data() {
    return {
      pickerValue: [0, 0, 0, 0],
      provinceDataList: [],
      cityDataList: [],
      areaDataList: [],
	  streetDataList: [],
		/* 是否显示控件 */
		showPicker: false,
    };
  },
  created() {
    this.init()
  },
  props: {
    /* 默认值 */
    pickerValueDefault: {
      type: Array,
      default(){
				return [0, 0, 0, 0]
			}
    },
    /* 主题色 */
    themeColor: String
  },
	watch:{
		pickerValueDefault(){
			this.init();
		}
	},
  methods: {
	init(code = 0, level = 'province') {
		console.log('8888:', code, level)
		// 每次滚动时初始化数据；
		switch (level){
			case 'province':
				this.cityDataList = [];
				this.areaDataList = [];
				this.streetDataList = [];
				break;
			case 'city':
				this.areaDataList = [];
				this.streetDataList = [];
				break;
			case 'district':
				this.streetDataList = [];
				break;
			default:
				break;
		}
		addressApis.getAddressClass(code, level).then(res => {
			// 获取第一层数据
			let { level: level1,  adcode} =  this.setLayerList(res, level);
			if (level1) {
				addressApis.getAddressClass(adcode, level1).then(res => {
					// 处理第二层数据
					let  { level: level2,  adcode}  = this.setLayerList(res, level1);
					console.log('res2:', res, level1, level2)
					if (level2) {
						addressApis.getAddressClass(adcode, level2).then(res => {
							console.log('res3:', res, level2)
							// 处理第三层数据
							let  { level: level3,  adcode}  = this.setLayerList(res, level2);
							if (level3) {
								addressApis.getAddressClass(adcode, level3).then(res => {
									// 处理第四层数据
									console.log('res4:', res, level3)
									this.streetDataList = res;
								})
							}
						})
					} else {
						return false;
					}
				})
			}
			return false;
		})
		this.handPickValueDefault(); // 对 pickerValueDefault 做兼容处理
	},
	setLayerList(res, currentLevel) {
		// 针对没有第三层数据的进行处理
		if (JSON.stringify(res) === '[]') {
			if(currentLevel === 'district') {
				this.areaDataList = res;
			} else {
				this.streetDataList = res;
			}
			return false;
		}
		const { adcode } = res[0];
		let level1 = currentLevel === 'province' ? 'city': (currentLevel === 'city' ? 'district' : (currentLevel === 'district' ? 'street': ''));
		switch (currentLevel){
			case 'province':
				this.provinceDataList = res;
				break;
			case 'city':
				this.cityDataList = res;
				break;
			case 'district':
				this.areaDataList = res;
				break;
			default:
				this.streetDataList = res;
				break;
		}
		return {level: level1, adcode};
	},
    show() {
      setTimeout(() => {
        this.showPicker = true;
      }, 0);
    },
    maskClick() {
      this.pickerCancel();
    },
    pickerCancel() {
      this.showPicker = false;
      this._$emit('onCancel');
    },
    pickerConfirm(e) {
      this.showPicker = false;
      this._$emit('onConfirm');
    },
    showPickerView() {
      this.showPicker = true;
    },
    handPickValueDefault() {
      if (this.pickerValueDefault !== [0, 0, 0, 0]) {
        if (this.pickerValueDefault[0] > this.provinceDataList.length - 1) {
          this.pickerValueDefault[0] = this.provinceDataList.length - 1;
        }
        if (this.pickerValueDefault[1] > this.cityDataList.length - 1) {
          this.pickerValueDefault[1] = this.cityDataList.length - 1;
        }
        if (this.pickerValueDefault[2] > this.areaDataList.length - 1) {
          this.pickerValueDefault[2] = this.areaDataList.length - 1;
        }
		if (this.pickerValueDefault[3] > this.streetDataList.length - 1) {
		  this.pickerValueDefault[2] = this.streetDataList.length - 1;	
		}
      }
    },
    pickerChange(e) {
      let changePickerValue = e.mp.detail.value;
      if (this.pickerValue[0] !== changePickerValue[0]) {
        // 第一级发生滚动 目前还未联调
		this.init(this.provinceDataList[changePickerValue[0]].adcode, 'city')
		changePickerValue[1] = 0;
		changePickerValue[2] = 0;
		changePickerValue[3] = 0;
      } else if (this.pickerValue[1] !== changePickerValue[1]) {
        // 第二级滚动
		this.init(this.cityDataList[changePickerValue[1]].adcode, 'district')
        changePickerValue[2] = 0;
		changePickerValue[3] = 0;
      } else if (this.pickerValue[2] !== changePickerValue[2]) {
        // 第三级滚动
		this.init(this.areaDataList[changePickerValue[2]].adcode, 'street')
		changePickerValue[3] = 0;
      }
      this.pickerValue = changePickerValue;
	  console.log('this.pickerValue:', this.pickerValue);
      this._$emit('onChange');
    },
    _$emit(emitName) {
      let pickObj = {
        label: this._getLabel(),
        value: this.pickerValue,
        city: this._getCityCode(),
		province: this._getProvinceCode(),
		district: this._getAreaCode(),
		street: this._getStreetCode()
      };
      this.$emit(emitName, pickObj);
    },
    _getLabel() {
      let pcikerLabel =
        this.provinceDataList[this.pickerValue[0]].name +
        '-' +
        (this.cityDataList[this.pickerValue[1]] ? '-' + this.cityDataList[this.pickerValue[1]].name : '') + 
		(this.areaDataList[this.pickerValue[2]] ? '-' + this.areaDataList[this.pickerValue[2]].name : '')+
        (this.streetDataList[this.pickerValue[3]] ? '-' + this.streetDataList[this.pickerValue[3]].name : '');
      return pcikerLabel;
    },
	_getProvinceCode() {
	  return this.provinceDataList[this.pickerValue[0]].adcode;
	},
	_getCityCode() {
	  return this.cityDataList[this.pickerValue[1]].adcode;
	},
	_getAreaCode() {
	  return this.areaDataList[this.pickerValue[2]].adcode;
	},
	_getStreetCode() {
	  return this.streetDataList[this.pickerValue[3]].adcode;
	}
  }
};
</script>

<style>
.pickerMask {
  position: fixed;
  z-index: 1000;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
}
.mpvue-picker-content {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  transition: all 0.3s ease;
  transform: translateY(100%);
  z-index: 3000;
}
.mpvue-picker-view-show {
  transform: translateY(0);
}
.mpvue-picker__hd {
  display: flex;
  padding: 9px 15px;
  background-color: #fff;
  position: relative;
  text-align: center;
  font-size: 17px;
}
.mpvue-picker__hd:after {
  content: ' ';
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  height: 1px;
  border-bottom: 1px solid #e5e5e5;
  color: #e5e5e5;
  transform-origin: 0 100%;
  transform: scaleY(0.5);
}
.mpvue-picker__action {
  display: block;
  flex: 1;
  color: #1aad19;
}
.mpvue-picker__action:first-child {
  text-align: left;
  color: #888;
}
.mpvue-picker__action:last-child {
  text-align: right;
}
.picker-item {
  text-align: center;
  line-height: 40px;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 16px;
}
.mpvue-picker-view {
  position: relative;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 238px;
  background-color: rgba(255, 255, 255, 1);
}
</style>
